package com.stgy.lease.web.admin.controller.attr;

import com.stgy.lease.common.redis.RedisPrefixEnum;
import com.stgy.lease.common.result.Result;
import com.stgy.lease.model.domain.AttrKey;
import com.stgy.lease.web.admin.service.AttrKeyService;
import com.stgy.lease.web.admin.vo.AttrKeyVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:AttrKeyController
 * Package:com.stgy.lease.web.admin.controller
 * Description:
 *
 * @Author:helei
 * @Create:2024/8/30 - 14:06
 */
@RestController
@RequestMapping("/admin/attr")
@Tag(name = "房间属性管理模块")
public class AttrKeyController {

    @Autowired
    private AttrKeyService attrKeyService;

    @Autowired
    private RedisTemplate redisTemplate;

    private String attrKeyVoListKey = RedisPrefixEnum.STGY_ADMIN_PREFIX + "attr:key:vo:list";

    /*
        设计接口：
            1、前端提交的参数 后端是否有实体类可以直接接收 dto
            2、后端响应的结果，如何安装前端的要求封装 创建实体类组装 vo
     */

    /**
     * id name attrValueList{id name attrKeyId}
     * id name List<AttrValue> attrValueList
     *
     * @return
     */
    //http://localhost:5174/admin/attr/list GET
    //select k.id, k.name, v.id vId, v.name vName, v.attr_key_id from attr_key k
    // left join attr_value v on k.id = v.attr_key_id where k.is_deleted = 0 and v.is_deleted = 0
    @Operation(summary = "查询所有属性和属性值集合")
    @GetMapping("/list")
    public Result<List<AttrKeyVo>> list() {
        List<AttrKeyVo> attrKeyVos = (List<AttrKeyVo>) redisTemplate.opsForValue().get(attrKeyVoListKey);
        if (attrKeyVos == null) {
            attrKeyVos = attrKeyService.listAttrKeyVos();
            redisTemplate.opsForValue().set(attrKeyVoListKey, attrKeyVos, 1, TimeUnit.DAYS);
        }
        return Result.ok(attrKeyVos);
    }

       //http://localhost:5174/admin/attr/key/saveOrUpdate post
    @Operation(summary = "增加或更新属性")
    @PostMapping("/key/saveOrUpdate")
    public Result<String> saveOrUpdate(@RequestBody AttrKey attrKey) {
        boolean b = attrKeyService.saveOrUpdateKey(attrKey);
        if (b) {
            redisTemplate.delete(attrKeyVoListKey);
        }
        return Result.build(b);
    }

    //http://localhost:5174/admin/attr/key/deleteById?attrKeyId=1829410050716856322 DELETE
    @Operation(summary = "删除房间的属性和值")
    @DeleteMapping("/key/deleteById")
    public Result<String> deleteById(@RequestParam("attrKeyId") List<Long> ids) {
        boolean b = attrKeyService.deleteByIds(ids);
        if (b) {
            redisTemplate.delete(attrKeyVoListKey);
        }
        return Result.build(b);
    }

}
